<!--
 * @Author: 王鹏 2911783749@qq.com
 * @Date: 2022-10-26 14:42:18
 * @LastEditors: 王鹏 2911783749@qq.com
 * @LastEditTime: 2022-10-27 19:09:16
 * @FilePath: \v_shop\code\src\components\children\Cate.vue
 * @Description: 商品分类页
-->
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :expand-type="false"
        :data="categoriesList"
        :columns="columns"
        show-index
        index-text="#"
        :selection-type="false"
      >
        <!-- 是否有效 -->
        <template slot="isOK" slot-scope="scope">
          <i
            class="el-icon-success"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 添加分类对话框 -->
      <el-dialog title="添加分类" :visible.sync="dialogVisible" width="50%">
        <el-form
          ref="addCateFormRef"
          :model="addCateForm"
          :rules="addCateFormRules"
          label-width="100px"
        >
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类:">
            <!-- 
              options：数据源
              props：靶子对象{
                value:选中的属性
                label:显示的名称
                children:嵌套的结构（靶子对象的连接点）
                ...
              }
              v-model:默认选中的数组
              @changed:选择项发生变化的时候触发的函数
             -->
            <el-cascader
              v-model="selectedKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentCateListChanged"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类对话框 -->
      <el-dialog title="" :visible.sync="editDialogVisible" width="50%">
        <el-form
          ref="editCateFormRef"
          :model="editCateForm"
          :rules="editCateFormRules"
          label-width="80px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCategories">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pqgenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {
  get_categoriesList,
  add_categories,
  del_categories,
  edit_categories,
} from "../../http/api";
export default {
  name: "categories",
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      // 
      categoriesList: [],
      //   靶子对象
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isOK",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      // 控制对话框显隐
      dialogVisible: false,
      // 编辑对话框的显隐
      editDialogVisible: false,
      // 添加分类表单
      addCateForm: {
        cat_name: "",
        // 父级分类id，默认为0那么0就代表一级分类，也就是默认添加的就是一级分类
        cat_pid: 0,
        // 父类的等级，默认的添加就是一级分类
        cat_level: 0,
      },
      // 编辑分类表单
      editCateForm: {
        cat_name: "",
      },
      // 添加分类表单校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
      },
      editCateFormRules: {
        cat_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
      },
      // 父级分类（1、2级）
      parentCateList: [],
      // 级联选择器的靶子对象
      cascaderProps: {
        label: "cat_name",
        expandTrigger: "hover",
        children: "children",
        checkStrictly: true, //可以选择任意一级
        value: "cat_id",
      },
      // 选中的父级分类的id
      selectedKeys: [],
    };
  },

  components: {},

  computed: {},

  mounted() {
    this.getAllCateories();
  },

  methods: {
    // 更改每页条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getAllCateories();
    },
    // 更改当前页数
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getAllCateories();
    },
    // 获取分类数据
    async getAllCateories() {
      let { data: res } = await get_categoriesList(this.queryInfo);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类数据失败");
      }
      this.categoriesList = res.data.result;
      this.total = res.data.total;
    },
    // 显示弹框
    async showDialog() {
      this.dialogVisible = true;
      let { data: res } = await get_categoriesList({ type: 2 });
      console.log(res);
      this.parentCateList = res.data;
    },
    // 级联选择器选择项发生变化时触发
    parentCateListChanged() {
      console.log(this.selectedKeys);
      // 级联选择器没有被选中那么就是一级分类
      if (this.selectedKeys.length === 0) {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      } else {
        // 二级分类或三级分类的判断
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
      }
    },
    // 添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await add_categories(this.addCateForm);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        this.$message.success("添加分类成功");
        this.dialogVisible = false;
        this.getAllCateories();
      });
    },
    // 分类编辑数据回填
    editCate(value) {
      this.editDialogVisible = true;
      this.editCateForm = {
        cat_id:value.cat_id,
        cat_name: value.cat_name,
      };
    },
    // 分类编辑
    async editCategories(){
      let {data:res} = await edit_categories(this.editCateForm)
      console.log(res);
      if(res.meta.status!==200){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.editDialogVisible=false
      this.getAllCateories();
    },
    // 删除分类
    async delCate(cat_id) {
      let { data: res } = await del_categories(cat_id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getAllCateories();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  watch: {},
  mixins: [],
};
</script>
<style  scoped>
.el-card {
  margin-top: 20px;
}
</style>
